<?php

class Admin_Model_DbMapper_Reviews extends Wlib_Model_DbMapper_SystemEntity
{
    protected $photoUrl, $smallPhotoUrl;
    protected $width = 120;
    protected $height = 120;

    public function getPhotoUrl() {return $this->photoUrl;}
    public function getSmallPhotoUrl() {return $this->smallPhotoUrl;}

    public function __construct()
    {
        $this->uploadPath = 'uploads/' . SITE_DOMAIN . '/reviews/';
    }

    public function getList()
    {
        $select = $this->select();
        $select->order('id ASC');

        return $this->getDbTable()->fetchAll($select);
    }

    public function savePhoto()
    {

        if(!isset($_FILES['photo']) || $_FILES['photo']['error'] == 4) {
            return;
        }

        if(!is_uploaded_file($_FILES['photo']["tmp_name"])) {
            throw new Exception('Ошибка загрузки файла');
        }

        require_once(APPLICATION_PATH . '/../library/WideImage/WideImage.php');

        $filename =  uniqid('prefix').time() . '.' . pathinfo($_FILES["photo"]['name'], PATHINFO_EXTENSION);

        $isMove = move_uploaded_file($_FILES["photo"]["tmp_name"], $this->uploadPath . $filename);

        if(!$isMove) {
            throw new Exception('Ошибка переноса файла!');
        }

        $this->photoUrl =  $this->uploadPath . $filename;
        $this->smallPhotoUrl = $this->uploadPath . '/thumbs/small_' . $filename;

        $result = WideImage::load($this->uploadPath . $filename)
            ->resize($this->width, $this->height)
            ->saveToFile($this->smallPhotoUrl);

        return true;
    }

    public function getUploadPath() {
        return $this->uploadPath;
    }

    /***
     *  Удаление отзывов
     */
    public function fullDeleteById($id)
    {
        $data = $this->selectById($id);

        if(count($data)) {
            // · удаляем из БД
            $this->deleteById($id);

            // · удаляем файлы
            if(isset($data['photo_url']) && $data['photo_url']) {
                unlink($data['photo_url']);
            }

            if(isset($data['small_photo_url']) && $data['small_photo_url']) {
                unlink($data['small_photo_url']);
            }
        }
    }



}
?>